# @Time    : 2024/2/15 17:02
# @Author  : 🍁
# @File    : file.py
# @Software: PyCharm

from django import forms
from django.core.validators import ValidationError

from web.models import File
from web.forms import bootstrap
from web.utils.cos.cos import check_file

from qcloud_cos.cos_exception import CosServiceError


class FileForms(bootstrap.BootStrap, forms.ModelForm):
    class Meta:
        model = File
        fields = ["title"]

    def __init__(self, request, folder_object, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        self.folder_object = folder_object

    def clean_title(self):
        title = self.cleaned_data["title"]
        file_object = File.objects.filter(type=2, title=title, project_id=self.request.tartec.project)
        if self.folder_object:  # 是否进入到了文件夹里面
            # 查看当前项目下的当前文件夹是否有重名的
            exists = file_object.filter(parent_id=self.folder_object.id).exists()

        else:
            # 查看主页目录下的文件夹是否有重名
            exists = file_object.filter(parent_id__isnull=True).exists()
        if exists:
            raise ValidationError("文件夹重名")
        return title


class FileModel(forms.ModelForm):
    etag = forms.CharField(label="ETag", max_length=128)

    class Meta():
        model = File
        fields = ["title", 'size', "key", "parent_id", "file_path", "etag"]

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_file_path(self):
        return "https://{}".format(self.cleaned_data["file_path"])

    def clean(self):
        key = self.cleaned_data["key"]
        etag = self.cleaned_data["etag"]
        size = self.cleaned_data["size"]
        if not key and not etag:
            return self.cleaned_data

        # 校验cos 文件是否合法
        try:
            result = check_file(self.request.tartec.project.bucket, self.request.tartec.project.region, key)
        except CosServiceError as e:
            self.add_error("key", "该文件不存在")
            return self.cleaned_data
        res_etag = result.get("ETag")
        if etag != res_etag:  # 判断etag 是否一致
            self.add_error("etag", "ETag错误")
            return self.cleaned_data

        return self.cleaned_data
